//
//  ActivityandPreViewController.m
//  CwinCar
//
//  Created by dllo on 15/10/21.
//  Copyright © 2015年 dlios. All rights reserved.
//

#import "ActivityandPreViewController.h"
#import "BaseHeader.h"

#import "PreferentialTableViewCell.h"

#import "ActivytyTableViewCell.h"

#import "ActivityModel.h"

#import "PreferentialModel.h"

#import "PreViewController.h"

#import "ActivityViewController.h"
#import "DataBase.h"
@interface ActivityandPreViewController ()<UITableViewDataSource , UITableViewDelegate , UIScrollViewDelegate >
{
    UISegmentedControl * _segmentPrefen ;
    NSInteger _collect ;
    UIButton *_backButton ;
}
@property (nonatomic , retain) UITableView * preferentialTableView ;

@property (nonatomic , retain) UITableView * activityTableView ;

@property (nonatomic , retain) NSMutableArray * preArray ;

@property (nonatomic , retain) NSMutableArray * activityArray ;

@property (nonatomic , retain) UIScrollView * scrollDi ;


@end

@implementation ActivityandPreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _preArray = [[NSMutableArray alloc]init];
    
    _activityArray = [[NSMutableArray alloc]init];
    
    
    NSArray *array = @[@"优惠",@"活动"];
    _segmentPrefen =[[UISegmentedControl alloc]initWithItems:array];
    _segmentPrefen.hidden = NO ;
    
    [_segmentPrefen setFrame:CGRectMake(0, 0, 150 * suitableScreen_Width, 40 * suitableScreen_Width)];
    [_segmentPrefen setCenter:CGPointMake(mainScreen_Width / 2, 20 * suitableScreen_Width)];
    
    [self.navigationController.navigationBar addSubview:_segmentPrefen];
    [_segmentPrefen addTarget:self action:@selector(segment : ) forControlEvents:UIControlEventValueChanged];
    
    [_segmentPrefen setTintColor:[UIColor whiteColor]];
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backButton.hidden = NO ;
    [_backButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_backButton];
    [_backButton setFrame:CGRectMake(mainScreen_Width / 22.058, 0, mainScreen_Width / 12.5, mainScree_Height / 22.233)];
    [_backButton setTintColor:[UIColor redColor]];
    [_backButton setTitleColor:[UIColor colorWithRed:0.088 green:0.331 blue:1.000 alpha:1.000] forState:UIControlStateSelected];
    
    [self.navigationController.navigationItem setHidesBackButton:YES];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationController.navigationBar.backItem setHidesBackButton:YES];
    [self creaView];
    [self addPrefenHeader];
    
    
    [self addActivityHeader];
    
    
    
    
}
- (void)backAction:(UIButton *)backBut
{
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
    _segmentPrefen.hidden = YES ;
    _backButton.hidden = YES ;
    
}
-(void)creaView
{
    _scrollDi = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, mainScree_Height)];
    [_scrollDi setContentSize : CGSizeMake(mainScreen_Width * 2 , 0)];
    
    [self.view addSubview:_scrollDi];
    [_scrollDi setPagingEnabled:YES];
    _scrollDi.delegate = self ;
    
    _preferentialTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,mainScreen_Width , mainScree_Height - 113 * suitableScreen_Width) style:UITableViewStylePlain];
    
    [_scrollDi addSubview:_preferentialTableView];
    
    _preferentialTableView.delegate = self ;
    
    _preferentialTableView.dataSource =self ;
    
    
    
    _activityTableView = [[UITableView alloc]initWithFrame:CGRectMake(mainScreen_Width,0, mainScreen_Width, mainScree_Height - 113 * suitableScreen_Width)style:UITableViewStylePlain];
    [_scrollDi addSubview:_activityTableView];
    
    _activityTableView.delegate = self ;
    
    _activityTableView.dataSource =self ;
    
    [_activityTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    
    
}

#pragma mark - segment点击方法

-(void)segment : (UISegmentedControl * )seg
{
    switch (seg.selectedSegmentIndex) {
        case 0:
            
            [_scrollDi setContentOffset:CGPointMake(0, 0)];
            
            break;
            
        case 1:
            [_scrollDi setContentOffset:CGPointMake(mainScreen_Width, 0)];
            
            break ;
            
        default:
            break;
    }
}

#pragma mark - scroll滚动方法

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_segmentPrefen setSelectedSegmentIndex:_scrollDi.contentOffset.x / mainScreen_Width];
    
    
    
}
#pragma mark 优惠
-(void)afndatanumber:(NSInteger)number
{
    [AFNblock getdataWithString:[NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/promotionList?areaId=1&pageNo=%ld&pageSize=20&orderBy=discountRange",(long)self.page]  block:^(id block) {
        NSMutableArray * dataArray = [block objectForKey:@"data"];
        
        for (NSMutableDictionary * dic in dataArray) {
            
            PreferentialModel * model = [[PreferentialModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [_preArray addObject:model];
            
        }
        [self addPrefenFooter];        [_preferentialTableView reloadData];
        [_preferentialTableView.header endRefreshing];
        [_preferentialTableView.footer endRefreshing];
    }];

}

#pragma mark 活动
-(void)activity : (NSInteger)number
{
    
    [AFNblock getdataWithString:[NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/activityListv45/1?pageNo=%ld&pageSize=20",(long)number] block:^(id block) {
        
        
        NSMutableArray * dataArray = [block objectForKey:@"data"];
        for (NSMutableDictionary * dic  in dataArray) {
            
            ActivityModel * model = [[ActivityModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [_activityArray addObject:model];
            
        }
        
        [_activityTableView reloadData];
        
        if (_activityTableView.footer == nil) {
            
            
            [self addActivityFooter];
        }
        
        [_activityTableView.header endRefreshing];
        [_activityTableView.footer endRefreshing];
    }];
    
}
#pragma mark - 优惠刷新加载
-(void)addPrefenHeader
{
    
    __block ActivityandPreViewController * vc = self ;
    [_preferentialTableView addLegendHeaderWithRefreshingBlock:^{
        vc.page = 1 ;
        [vc afndatanumber:vc.page];
        
    }] ;
    [_preferentialTableView.header beginRefreshing];
    
}

-(void)addPrefenFooter
{
    
    __block ActivityandPreViewController * vc = self ;
    
    [_preferentialTableView addLegendFooterWithRefreshingBlock:^{
        vc.page ++ ;
        
        [vc afndatanumber:vc.page];
        
    }];
    
    
}
#pragma mark - 活动刷新加载
-(void)addActivityHeader
{
    __block ActivityandPreViewController * vc = self ;
    
    [_activityTableView addLegendHeaderWithRefreshingBlock: ^{
        vc.page1 = 1 ;
        
        vc.isloading = NO ;
        
        [vc activity:vc.page1];
        
    }] ;
    
    [_activityTableView.header beginRefreshing];
}

-(void)addActivityFooter
{
    
    __block ActivityandPreViewController * vc = self ;
    
    [_activityTableView addLegendFooterWithRefreshingBlock:^{
        vc.page1 ++ ;
        
        [vc activity:vc.page1];
        
    }];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_preferentialTableView]) {
        
        
        return _preArray.count ;
    }
    else if ([tableView isEqual:_activityTableView])
    {
        
        return _activityArray.count ;
    }
    return 0 ;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([tableView isEqual:_preferentialTableView]) {
        
        return 150 * suitableScreen_Width ;
        
    }
    else if ([tableView isEqual:_activityTableView])
    {
        return 160 * suitableScreen_Width ;
    }
    
    return 0 ;
}

-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_preferentialTableView]) {
        
                [[DataBase shareDataBase]openDB];
        
                [[DataBase shareDataBase]createTable];
        
        
        static NSString * cellId = @"cell" ;
        
        PreferentialTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            
            cell = [[PreferentialTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            
        }
        
        [cell.buttonPhone addTarget:self action:@selector(phone : ) forControlEvents:UIControlEventTouchUpInside];
        cell.buttonPhone.tag = indexPath.row  ;
        
        PreferentialModel * model = [_preArray objectAtIndex:indexPath.row];
        [cell getPreModel:model];
        cell.buttonCollect.selected =NO;
         NSArray * array =   [[DataBase shareDataBase]selectAll];
                for (PreferentialModel * model1  in array) {
        
                    if ([model1.modelName isEqualToString:model.modelName]) {
        
                        cell.buttonCollect.selected = YES ;
                    }
                }
        [cell.buttonCollect addTarget:self action:@selector(collect : ) forControlEvents:UIControlEventTouchUpInside];
        cell.buttonCollect.tag = 10000 + indexPath.row ;
        return cell ;
    }
    
    else if ([tableView isEqual:_activityTableView])
    {
        
        static NSString * cellAc = @"cell" ;
        
        ActivytyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellAc];
        
        if (!cell) {
            
            
            cell = [[ActivytyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellAc];
            
        }
        
        ActivityModel  * model = [_activityArray objectAtIndex:indexPath.row];
        
        
        [cell activityGetModel:model];
        
        return cell ;
    }
    
    return nil ;
    
}
//收藏

-(void)collect : (UIButton * )sender
{

    NSArray *array = [[DataBase shareDataBase] selectAll];

    if (sender.selected == NO ) {

        PreferentialModel * model = [_preArray objectAtIndex:sender.tag - 10000];
        [[DataBase shareDataBase]insertStudent:model];

    }
    else
    {
        for (PreferentialModel * model in array) {
            PreferentialModel * model1 =[_preArray objectAtIndex:sender.tag - 10000] ;                         if ([model.modelName isEqualToString:model1.modelName]) {
                [[DataBase shareDataBase]deleteStudent:model.modelName];
            }
        }


    }


    sender.selected = !sender.selected ;

}


//打电话
-(void)phone : (UIButton * )sender
{
    PreferentialModel * model = [_preArray objectAtIndex:sender.tag ];
    
    NSString * p = [NSString stringWithFormat:@"tel://%@",model.phone];
    NSURL * url = [NSURL URLWithString:p];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"号码不可用\n或您的备设不支持拨号功能" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
    
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_preferentialTableView]) {
        
        PreViewController * pre = [[PreViewController alloc]init];
        pre.model = [_preArray objectAtIndex:indexPath.row];
        pre.hidesBottomBarWhenPushed = YES; // 隐藏tabbar
        [self.navigationController pushViewController:pre animated:YES];
    }
    else
    {
        ActivityViewController * act = [[ActivityViewController alloc]init];
        act.model = [_activityArray objectAtIndex:indexPath.row];
        act.hidesBottomBarWhenPushed = YES; // 隐藏tabbar
        [self.navigationController pushViewController:act animated:YES];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
